// ignore_for_file: must_be_immutable

/*
 * @Author: CodeHare
 * @Date: 2023-09-27 10:59:53
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-25 15:38:50
 * @Description: 站点数据总览页
 */

import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/common_chart.dart';
import 'package:yt_devops/components/format_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/components/timer_picker.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/pages/site/site_statis_data/show_full_screen_btn.dart';
import 'package:yt_devops/pages/site/site_statis_data/site_statis_data_controller.dart';
import 'package:yt_devops/pages/site/site_statis_data/widgtes/energy_bar_line.dart';
import 'package:yt_devops/pages/site/site_statis_data/widgtes/power_line_charts.dart';
import 'package:yt_devops/pages/site/site_statis_data/widgtes/site_overview_widget.dart';
import 'package:yt_devops/pages/site/site_statis_data/widgtes/site_overview_widgets.dart';
import 'package:yt_devops/pages/site/widgets/electricity_statistics_chart.dart';
import 'package:yt_devops/pages/site/widgets/full_screen_power_chart.dart';
import 'package:yt_devops/pages/site/widgets/full_screen_profit_chart.dart';
import 'package:yt_devops/pages/site/widgets/power_rank_tab.dart';
import 'package:yt_devops/pages/site/widgets/profit_chart.dart';
import 'package:yt_devops/pages/site/widgets/statistics_time_unit_tab.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';

class SiteStatisDataView extends GetView<SiteStatisDataController> {
  const SiteStatisDataView({Key? key}) : super(key: key);

  @override
  // final controller = Get.put(SiteStatisDataController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SiteStatisDataController>(
      builder: (controller) {
        return Scaffold(
            backgroundColor: Colour.backgroundColor,
            appBar: AppBarWidget.defaultAppBar(
              controller.siteName,
            ),
            body: Column(
              children: [
                /// 时间切换Tab
                Container(
                    margin: EdgeInsets.only(
                      left: 16.w,
                      right: 16.w,
                      top: 16,
                    ),
                    decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(8))),
                    child: Column(children: [
                      YtTimePicker(
                        pickerMode: DateTimePickerMode.all,
                        initialDateTime: DateTime(
                          controller.targetYear,
                          controller.targetMonth,
                          controller.targetDay,
                        ),
                        onChange: (date, StatisticUnitStatusType? statusType) =>
                            controller.echoDateAssign(date, statusType),
                      ),
                    ])),
                Expanded(
                  child: SmartRefresher(
                    controller: controller.refreshController,
                    enablePullDown: true,
                    enablePullUp: false,
                    header: ListTips.classicHeader,
                    onRefresh: () => controller.onRefresh(),
                    child: ListView(
                      children: <Widget>[
                        Gaps.vGap10,
                        //   SiteOverViewWidgets(energyData: controller.energyData,
                        // titleList: controller.state.siteOverviewTitles),
                        SiteOverviewWidget(
                            energyOptions: controller.energyOptions,
                            monetaryUnitName:controller.monetaryUnitName,
                            energyData: controller.energyData),
                        _esPowerStatics(),
                        Gaps.vGap10
                        // /// 收益图表
                        // _generateRevenueBarChart(),
                      ],
                    ),
                  ),
                ),
              ],
            ));
      },
    );
  }

  _esPowerStatics() {
    double width = TextWidth.calculateTextSize(ResKey.fullScreen.tr,
            ytTextStyle(fontSize: 12, color: Colour.otherTextColor)) +
        20;
    Log.d('_esPowerStatics==${controller.selectedType}');
    Log.d('statisticUnitType==${controller.statisticUnitType}');
    return Container(
      // height: 55 + 40 + 280 + 20,
      margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 10),
      padding: const EdgeInsets.only(
        top: 16,
      ),
      clipBehavior: Clip.antiAliasWithSaveLayer,
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(8))),
      child: Column(
        children: [
          // Gaps.vGap10,
          Container(
            color: Colors.white,
            child: PowerRankTab(
              controller.selectedType,
              (PowerRankTabType type) {
                controller.tabClick(type);
              },
              string1:
                  controller.statisticUnitType == StatisticUnitStatusType.day
                      // &&controller.energyOptions == '2'
                      ? ResKey.power.tr
                      : '',
              string2: ResKey.quantityOfElectricity.tr,
              string3: ResKey.income.tr,
            ),
          ),
          Row(
            children: [
              if (controller.selectedType == PowerRankTabType.power)
                _overviewOrDetail(),
              const Spacer(),
              ShowFullScreenBtn(onTap: () {
                if (controller.selectedType == PowerRankTabType.electricity) {
                  Navigator.push(
                    Get.context!,
                    MaterialPageRoute(
                      builder: (context) => FullScreenPowerChart(
                        data: controller.electricityBarChartList,
                        timeList: controller.electricityXAxisList,
                        // maxValue: controller.electricityMaxValue,
                        // minValue: controller.electricityMinValue,
                        paramList: controller.state.paramList,
                        tooltipFormatter: FormatUtil.getToolTipFormater(
                          timeType: controller.statisticUnitType,
                          chartType: 1,
                          selectedType: controller.selectedType,
                          time: DateTime(
                            controller.targetYear,
                            controller.targetMonth,
                            controller.targetDay,
                          ),
                        ),
                      ),
                    ),
                  );
                } else if (controller.selectedType == PowerRankTabType.profit) {
                  Navigator.push(
                    Get.context!,
                    MaterialPageRoute(
                        builder: (context) => FullScreenProfitChart(
                              data: controller.barProfitList,
                              paramList: controller.state.paramList,
                              timeList: controller.electricityXAxisList,
                              // maxValue: controller.profitMaxValue,
                              // minValue: controller.profitMinValue,
                              tooltipFormatter: FormatUtil.getToolTipFormater(
                                timeType: controller.statisticUnitType,
                                chartType: 1,
                                selectedType: controller.selectedType,
                                time: DateTime(
                                  controller.targetYear,
                                  controller.targetMonth,
                                  controller.targetDay,
                                ),
                              ),
                            )),
                  );
                } else if (controller.selectedType == PowerRankTabType.power) {
                  Get.toNamed(RouterPath.powerFullChart, arguments: {
                    'lineChart': controller.isOverview
                        ? controller.eChartPowerShowList
                        : controller.eChartPowerDetailShowList,
                    'xAxisList': controller.powerXAxisList,
                    'tooltipFormatter': FormatUtil.getToolTipFormater(
                      timeType: controller.statisticUnitType,
                      chartType: 0,
                      selectedType: controller.selectedType,
                      time: DateTime(
                        controller.targetYear,
                        controller.targetMonth,
                        controller.targetDay,
                      ),
                    ),
                  });
                }
              }),
            ],
          ),

          SizedBox(
            height: controller.selectedType == PowerRankTabType.power
                ? 210 + controller.showTitlesContainerHeight + 20
                : controller.selectedType == PowerRankTabType.electricity
                    ? 210 + controller.showElectricityHeight + 20
                    : 260,
            child: TabBarView(
                controller: controller.tabController,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  Visibility(
                      visible: controller.statisticUnitType ==
                          StatisticUnitStatusType.day,
                      // &&controller.energyOptions == '2',
                      child: Container(
                          // height: 210,
                          color: Colors.white,
                          child: Column(
                            children: [
                              Container(
                                height: 210,
                                margin:
                                    const EdgeInsets.only(top: 0, bottom: 5),
                                color: Colors.white,
                                child: PowerLineChart(
                                  data: controller.isOverview
                                      ? controller.eChartPowerShowList
                                      : controller.eChartPowerDetailShowList,
                                  timeList: controller.powerXAxisList,
                                  tooltipFormatter:
                                      FormatUtil.getToolTipFormater(
                                    timeType: controller.statisticUnitType,
                                    chartType: 0,
                                    selectedType: controller.selectedType,
                                    time: DateTime(
                                      controller.targetYear,
                                      controller.targetMonth,
                                      controller.targetDay,
                                    ),
                                  ),
                                ),
                              ),
                              _powerTypeWidget()
                            ],
                          ))),
                  Container(
                      margin: const EdgeInsets.only(bottom: 10),
                      // height: 230,
                      color: Colors.white,
                      child: Column(children: [
                        Container(
                          height: 210,
                          margin: const EdgeInsets.only(top: 0, bottom: 5),
                          color: Colors.white,
                          child: ElectricityStatisticsChart(
                            data: controller.eChartElectricityShowList,
                            timeList: controller.electricityXAxisList,
                            paramList: controller.state.paramList,
                            tooltipFormatter: FormatUtil.getToolTipFormater(
                              timeType: controller.statisticUnitType,
                              chartType: 1,
                              selectedType: controller.selectedType,
                              time: DateTime(
                                controller.targetYear,
                                controller.targetMonth,
                                controller.targetDay,
                              ),
                            ),
                          ),
                        ),
                        _electricityTypeWidget()
                      ])),
                  Container(
                      margin: const EdgeInsets.only(bottom: 10),
                      height: 230,
                      color: Colors.white,
                      child:
                          // CommonChartWidget(isValueType: true, yAxisDataSource: controller.barProfitList,
                          //   xAxisDataSource: controller.electricityXAxisList,)
                          ProfitChart(
                        profit: controller.barProfitList,
                        timeList: controller.electricityXAxisList,
                        paramList: controller.state.paramList,
                        tooltipFormatter: FormatUtil.getToolTipFormater(
                          timeType: controller.statisticUnitType,
                          chartType: 1,
                          selectedType: controller.selectedType,
                          time: DateTime(
                            controller.targetYear,
                            controller.targetMonth,
                            controller.targetDay,
                          ),
                        ),
                      )),
                ]),
          ),
        ],
      ),
    );
  }

  _electricityTypeWidget() {
    return
        // ClipRect(child:
        Container(
      key: controller.electricityTitlesKey,
      // height: 80,
      margin: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
      ),
      color: Colors.white,
      child: Wrap(
          direction: Axis.horizontal,
          spacing: 5,
          runSpacing: 5,
          textDirection: TextDirection.ltr,
          children: _getElectricityShowList()),
      // )
    );
  }

  List<Widget> _getElectricityShowList() {
    List<Widget> list = [];
    if (controller.state.showElectricityTitles.isNotEmpty) {
      for (var element in controller.state.showElectricityTitles) {
        list.add(_powerTypeItem(
            element['title'], element['color'], element['isShow'], true));
      }
    }
    return list;
  }

  _powerTypeWidget() {
    return
        // ClipRect(child:
        Container(
      key: controller.showTitlesKey,
      // height: 80,
      margin: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
      ),
      color: Colors.white,
      child: Wrap(
          direction: Axis.horizontal,
          spacing: 5,
          runSpacing: 5,
          textDirection: TextDirection.ltr,
          children: _getShowList()),
      // )
    );
  }

  List<Widget> _getShowList() {
    List<Widget> list = [];
    if (controller.isOverview) {
      if (controller.state.chartShowTitles.isNotEmpty) {
        for (var element in controller.state.chartShowTitles) {
          list.add(_powerTypeItem(
              element['title'], element['color'], element['isShow'], false));
        }
      }
    } else {
      if (controller.state.chartShowDetailTitles.isNotEmpty) {
        for (var element in controller.state.chartShowDetailTitles) {
          list.add(_powerTypeItem(
              element['title'], element['color'], element['isShow'], false));
        }
      }
    }

    return list;
  }

  _powerTypeItem(
      String title, String colorString, bool isShow, bool isElectricity) {
    Color color = Colour.grayE7Color;
    if (colorString.isNotEmpty && colorString.contains('#')) {
      color = Color(int.parse(colorString.replaceAll('#', '0xFF')));
    }
    var textWidth = TextWidth.calculateTextSize(title, ytTextStyle());
    return MyGestureDetector(
        onTap: () {
          if (isElectricity) {
            controller.hiddenOrShowElectricity(title);
          } else {
            controller.hiddenOrShowData(title);
          }
        },
        child: Container(
          color: Colors.white,
          alignment: Alignment.center,
          width: textWidth + 20,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(1.5),
                  color: isShow ? color : Colour.grayE7Color,
                ),
                height: 3,
                width: 12,
              ),
              const SizedBox(
                width: 5,
              ),
              Text(
                title,
                style: ytTextStyle(),
              ),
            ],
          ),
        ));
  }

  //概览和详情切换
  _overviewOrDetail() {
    return Container(
        // color: Colors.red,
        alignment: Alignment.center,
        height: 40,
        width: 150.w,
        margin: EdgeInsets.only(left: 16.w),
        padding: EdgeInsets.only(top: 10),
        child: Row(
          children: [
            MyGestureDetector(
                onTap: () {
                  controller.powerOverviewClick();
                },
                child: Container(
                  child: Text(
                    ResKey.overview.tr,
                    style: ytTextStyle(
                        fontSize: controller.isOverview ? 16 : 14,
                        fontWeight: FontWeight.w500,
                        color: controller.isOverview
                            ? Colour.mainTextColor
                            : Colour.mainTextColor.withOpacity(0.6)),
                  ),
                )),
            Gaps.hGap10,
            MyGestureDetector(
                onTap: () {
                  controller.powerDetailClick();
                },
                child: Container(
                  child: Text(
                    ResKey.detail.tr,
                    style: ytTextStyle(
                        fontSize: !controller.isOverview ? 16 : 14,
                        fontWeight: FontWeight.w500,
                        color: controller.isOverview
                            ? Colour.mainTextColor.withOpacity(0.6)
                            : Colour.mainTextColor),
                  ),
                )),
          ],
        ));
  }
}
